package bblgw

import (
	"net"
	"net/http"
	"time"
)

const (
	MAJOR_VERSION       = "0"
	MINOR_VERSION       = "1"
	SERVER_NAME         = "bgw"
	CLUSTER_NAME_PREFIX = "bgw-"
	Author              = "G.Q.F"
	Mail                = "gao.qingfeng@gmail.com"
	License             = "GPL"
)

func version() string {
	return MAJOR_VERSION + "." + MINOR_VERSION
}

func server_name() string {
	return SERVER_NAME + "/" + version()
}

func copyright() string {
	return "Server: " + server_name() + "\nAuthor: " + Author + "\nMail: " + Mail + "\nLicense: " + License
}

type GatewayServer struct {
	Listen     string
	UnixSock   string
	Slaves     []string
	Master     string
	Cachedir   string
	Passphrase string
	listener   net.Listener
	unixsock   net.Listener
}

func (v *GatewayServer) Init() error {
	ll, e := net.Listen("tcp", v.Listen)
	if e != nil {
		log.Error(e)
		return e
	}
	v.listener = ll
	if v.UnixSock != "" {
		ul, e := net.Listen("unix", v.UnixSock)
		if e != nil {
			log.Error(e)
			return e
		}
		v.unixsock = ul
	}

	return nil
}
func (v *GatewayServer) Serve() {
	handler := NewGatewayMux(gw_conf)
	if v.unixsock != nil {
		unixserver := http.Server{
			ReadTimeout:    90 * time.Minute,
			WriteTimeout:   90 * time.Minute,
			MaxHeaderBytes: 1 << 20,
			Handler:        handler,
		}
		unixserver.SetKeepAlivesEnabled(true)
		go unixserver.Serve(v.unixsock)
	}

	server := http.Server{
		ReadTimeout:    90 * time.Minute,
		WriteTimeout:   90 * time.Minute,
		MaxHeaderBytes: 1 << 20,
		Handler:        handler,
	}
	server.SetKeepAlivesEnabled(true)
	log.Info("gateway server  listen at " + v.Listen)
	server.Serve(v.listener)
}

func (v *GatewayServer) Stop() {
	if v.unixsock != nil {
		v.unixsock.Close()
		v.unixsock = nil
	}
	if v.listener != nil {
		v.listener.Close()
		v.listener = nil
		log.Info("gateway server stopped")
	}
}
